#!/bin/bash

function log() {
  msg="$*"
  logger -t mythtvsystem "$msg"
}

# Read the provided configuration
[ -z "$1" ] && log "No configuration file! (using all defaults)"
[ -n "$1" -a -f "$1" ] && source $1

LOGFILE=${LOGFILE:-$HOME/mythtvsystem.log}
[ -f $LOGFILE ] && mv $LOGFILE ${LOGFILE}.bak

# Autoconfigure LinEAK with given keyboard.
LINEAKD=$(which lineakd)
LINEAKCONFIG=$HOME/.lineak/lineakd.conf
if [ -n "$LINEAKD" ]; then
    TMPCONFIG=/tmp/lineakd_$$.conf
    if [ -f $LINEAKCONFIG ]; then
	cp $LINEAKCONFIG $TMPCONFIG
	PREVIOUS_MIXER=$(grep MixerDevice $TMPCONFIG | sed 's/.*= *\([^ ]*\).*$/\1/g')
	MIXER_DEVICE=${MIXER_DEVICE:-$PREVIOUS_MIXER}
    else
	if [ -n "$LINEAK_KEYBOARD" ]; then
            log "configuring for keyboard type '$LINEAK_KEYBOARD'"
	    $LINEAKD -f $TMPCONFIG -c $LINEAK_KEYBOARD 2> /dev/null
	else
	    log "No keyboard configured with LINEAK_KEYBOARD! (Not started)"
	fi	
    fi

    if [ -z "$MIXER_DEVICE" ]; then
	MIXER_DEVICE=$(ls /dev/sound/mixer* /dev/mixer* 2>/dev/null | head -n 1)
	log "Auto-detected mixer device $MIXER_DEVICE"
    fi
    if [ -f $TMPCONFIG ]; then
	cat $TMPCONFIG \
	| sed -e 's/\(VolumeDown *= *\)/\1EAK_VOLDOWN/g' \
	      -e 's/\(VolumeUp *= *\)/\1EAK_VOLUP/g' \
	      -e 's/\(Mute *= *\)/\1EAK_MUTE/g' \
	      -e "s,MixerDevice *=.*,MixerDevice = ${MIXER_DEVICE},g" \
	      -e "s,conffilename *=.*,conffilename = ${LINEAKCONFIG},g" \
          > $LINEAKCONFIG
	rm -f $TMPCONFIG
    fi
fi

# Make sure we have a suitable .xinitrc file
XINITRC=$HOME/.xinitrc_mythtv
if [ ! -f $HOME/.xinitrc ]; then
  XINITRC=$HOME/.xinitrc
fi
export XINITRC
echo "# MythTV System startup script" > $XINITRC
EMPTY_CURSOR=$HOME/.blank_cursor
rm -f $EMPTY_CURSOR
touch $EMPTY_CURSOR
echo "xsetroot -solid black -cursor $EMPTY_CURSOR $EMPTY_CURSOR" >> $XINITRC
echo "xset -dpms s off" >> $XINITRC
[ -f $LINEAKCONFIG ] && echo "$LINEAKD 2>/dev/null &" >> $XINITRC
echo "exec mythfrontend --logfile $LOGFILE" >> $XINITRC
chmod 755 $XINITRC

# Make sure we start all the stuff 
/usr/bin/startx
